module EX_MEM(
    input wire we,
    input wire clk,
    input wire reset,
    input wire is_write_reg_in,//if the instrcution write the register
    input wire is_write_mem_in,//if the instrcution write the memory
    input wire res_from_mem_in,//result source
    input wire [3:0] mem_op_in,
    input wire [4:0] dest_in,
    input wire [31:0] pc_in,
    input wire [31:0] alu_result_in,
    input wire [31:0] rf_rdata2_after_forward_in,
//csr
    input wire is_write_csr_in,
    input wire [13:0]csr_dest_in,
    input wire [31:0]csr_wdata_in,
    input wire [31:0]csr_rdata_in,
    input wire res_from_csr_in,


    output reg is_write_reg,//if the instrcution write the register
    output reg is_write_mem,//if the instrcution write the memory
    output reg res_from_mem,//result source
    output reg [3:0] mem_op,
    output reg [4:0] dest,
    output reg [31:0] pc,
    output reg [31:0] alu_result,
    output reg [31:0] fdata,
    output reg[31:0] rf_rdata2_after_forward,
//csr
    output reg is_write_csr,
    output reg [13:0]csr_dest,
    output reg [31:0]csr_wdata,
    output reg [31:0]csr_rdata,
    output reg res_from_csr,

    input wire exc_in,
    input wire [5:0] ecode_in,
    input wire esubcode_in,
    input wire[31:0] badv_in,
    
    output reg exc,
    output reg [5:0] ecode,
    output reg esubcode,
    output reg[31:0] badv
    );

    always@(posedge clk)begin
        if(reset)begin
            res_from_mem<=0;
            is_write_reg<=0;
            is_write_mem<=0;
            mem_op<=0;
            dest<=0;
            pc<=0;
            alu_result<=0;
            fdata<=0;
            rf_rdata2_after_forward<=0;
            is_write_csr<=0;
            csr_dest<=0;
            csr_wdata<=0;
            csr_rdata<=0;
            res_from_csr<=0;
            exc<=0;
            ecode<=0;
            esubcode<=0;
            badv<=0;
        end
        else if(we)begin
            res_from_mem<=res_from_mem_in & ~exc_in;
            is_write_reg<=is_write_reg_in & ~exc_in;
            is_write_mem<=is_write_mem_in & ~exc_in;
            mem_op<=mem_op_in;
            dest<=dest_in;
            pc<=pc_in;
            alu_result<=alu_result_in;
            fdata <= res_from_csr_in ? csr_rdata_in : alu_result_in;
            rf_rdata2_after_forward<=rf_rdata2_after_forward_in;
            is_write_csr<=is_write_csr_in & ~exc_in;
            csr_dest<=csr_dest_in;
            csr_wdata<=csr_wdata_in;
            csr_rdata<=csr_rdata_in;
            res_from_csr<=res_from_csr_in;
            exc<=exc_in;
            ecode<=ecode_in;
            esubcode<=esubcode_in;
            badv<=badv_in;
        end
    end
endmodule
